"""
系统管理相关的请求/响应模型
包括角色、权限、用户管理、审计日志等接口的Schema定义
"""
from datetime import datetime
from typing import Optional, List, Annotated, Union

from pydantic import BaseModel, Field, ConfigDict, BeforeValidator

from app.models.system_models import PermissionType, RoleType
from app.schemas.alarm_schemas import empty_str_to_none


# ============ 角色相关 Schema ============

class RoleBase(BaseModel):
	"""角色基础模型"""
	role_code: str = Field(..., min_length=1, max_length=32, description="角色编码")
	role_name: str = Field(..., min_length=1, max_length=64, description="角色名称")
	description: Optional[str] = Field(None, max_length=255, description="角色描述")
	type: RoleType = Field(RoleType.CUSTOM, description="角色类型")


class RoleCreate(RoleBase):
	"""创建角色请求模型"""
	pass


class RoleUpdate(BaseModel):
	"""更新角色请求模型"""
	role_name: Optional[str] = Field(None, min_length=1, max_length=64, description="角色名称")
	description: Optional[str] = Field(None, max_length=255, description="角色描述")
	enabled: Optional[bool] = Field(None, description="启用状态")


class RoleResponse(RoleBase):
	"""角色响应模型"""
	id: int
	enabled: bool
	version: int
	gmt_create: datetime
	gmt_update: datetime

	model_config = ConfigDict(from_attributes=True)


class RoleWithPermissionsResponse(RoleResponse):
	"""带权限的角色响应模型"""
	permissions: List["PermissionResponse"] = []


# ============ 权限相关 Schema ============

class PermissionBase(BaseModel):
	"""权限基础模型"""
	perm_code: str = Field(..., min_length=1, max_length=64, description="权限编码")
	perm_name: str = Field(..., min_length=1, max_length=64, description="权限名称")
	type: PermissionType = Field(PermissionType.API, description="权限类型")
	parent_id: int = Field(0, description="父权限ID")
	path: Optional[str] = Field(None, max_length=500, description="权限路径")
	level: int = Field(1, ge=1, le=10, description="层级深度")
	sort: int = Field(0, ge=0, description="排序")


class PermissionCreate(PermissionBase):
	"""创建权限请求模型"""
	pass


class PermissionUpdate(BaseModel):
	"""更新权限请求模型"""
	perm_name: Optional[str] = Field(None, min_length=1, max_length=64, description="权限名称")
	type: Optional[PermissionType] = Field(None, description="权限类型")
	parent_id: Optional[int] = Field(None, description="父权限ID")
	path: Optional[str] = Field(None, max_length=500, description="权限路径")
	level: Optional[int] = Field(None, ge=1, le=10, description="层级深度")
	sort: Optional[int] = Field(None, ge=0, description="排序")


class PermissionResponse(PermissionBase):
	"""权限响应模型"""
	id: int
	gmt_create: datetime

	model_config = ConfigDict(from_attributes=True)


class PermissionTreeResponse(PermissionResponse):
	"""权限树形响应模型"""
	children: List["PermissionTreeResponse"] = []


# ============ 用户角色相关 Schema ============

class UserRoleAssignRequest(BaseModel):
	"""用户角色分配请求模型"""
	user_code: str = Field(..., description="用户编码")
	role_ids: List[int] = Field(..., description="角色ID列表")


class RolePermissionAssignRequest(BaseModel):
	"""角色权限分配请求模型"""
	role_id: int = Field(..., description="角色ID")
	permission_ids: List[int] = Field(..., description="权限ID列表")


# ============ 用户管理相关 Schema ============

class UserListRequest(BaseModel):
	"""用户列表查询请求模型"""
	page: int = Field(1, ge=1, description="页码")
	size: int = Field(20, ge=1, le=100, description="每页大小")
	username: Optional[str] = Field(None, description="用户名筛选")
	name: Optional[str] = Field(None, description="姓名筛选")
	role_id: Optional[int] = Field(None, description="角色ID筛选")
	disabled: Optional[bool] = Field(None, description="状态筛选")


class UserWithRolesResponse(BaseModel):
	"""带角色的用户响应模型"""
	id: int
	user_code: str
	username: str
	name: str
	email: str
	phone: Optional[str] = None
	disabled: bool
	created_at: datetime
	updated_at: datetime
	last_login: Optional[datetime] = None
	roles: List[RoleResponse] = []

	model_config = ConfigDict(from_attributes=True)


class UserListResponse(BaseModel):
	"""用户列表响应模型"""
	total: int
	items: List[UserWithRolesResponse]


# ============ 审计日志相关 Schema ============

class AuditLogRequest(BaseModel):
	"""审计日志查询请求模型"""
	page: int = Field(1, ge=1, description="页码")
	size: int = Field(20, ge=1, le=100, description="每页大小")
	user_id: Optional[str] = Field(None, description="用户编码筛选")
	action: Optional[str] = Field(None, description="操作类型筛选")
	target_type: Optional[str] = Field(None, description="目标类型筛选")
	start_time: Optional[datetime] = Field(None, description="开始时间")
	end_time: Optional[datetime] = Field(None, description="结束时间")
	result: Optional[bool] = Field(None, description="结果筛选")


class AuditLogResponse(BaseModel):
	"""审计日志响应模型"""
	id: int
	user_id: Optional[str] = None
	username: Optional[str] = None  # 关联查询用户名
	action: str
	target_type: str
	target_id: str
	request_ip: str
	request_uri: str
	result: bool
	gmt_create: datetime

	model_config = ConfigDict(from_attributes=True)


class AuditLogListResponse(BaseModel):
	"""审计日志列表响应模型"""
	total: int
	items: List[AuditLogResponse]


# ============ 角色列表相关 Schema ============

class RoleListRequest(BaseModel):
	"""角色列表查询请求模型"""
	page: int = Field(1, ge=1, description="页码")
	size: int = Field(20, ge=1, le=100, description="每页大小")
	role_name: Optional[str] = Field(None, description="角色名称筛选")
	role_code: Optional[str] = Field(None, description="角色编号筛选")
	type: Annotated[Union[str, None], BeforeValidator(empty_str_to_none)] = Field(
		None, description="角色类型筛选"
	)
	enabled: Optional[bool] = Field(None, description="启用状态筛选")


class RoleListResponse(BaseModel):
	"""角色列表响应模型"""
	total: int
	items: List[RoleWithPermissionsResponse]


class PermissionListRequest(BaseModel):
	"""权限列表查询请求模型"""
	page: int = Field(1, ge=1, description="页码")
	size: int = Field(20, ge=1, le=100, description="每页大小")
	perm_name: Optional[str] = Field(None, description="权限名称模糊查询")
	perm_code: Optional[str] = Field(None, description="权限编码模糊查询")
	type: Optional[PermissionType] = Field(None, description="权限类型筛选")


class PermissionListResponse(BaseModel):
	"""权限列表响应模型"""
	total: int
	items: List[PermissionResponse]


class OperationStatisticsResponse(BaseModel):
	"""操作统计响应模型"""
	action_stats: List[dict] = Field(description="按动作分组统计")
	user_stats: List[dict] = Field(description="按用户分组统计")
	daily_stats: List[dict] = Field(description="按日期分组统计")
	result_stats: dict = Field(description="按结果分组统计")


# ============ 设备负责人相关 Schema ============

class ManagerUpdateRequest(BaseModel):
	"""设备负责人更新请求模型"""
	manager_code: str = Field(..., min_length=1, max_length=32, description="负责人工号")


# 解决循环引用问题
RoleWithPermissionsResponse.model_rebuild()
PermissionTreeResponse.model_rebuild()
